filename = 'flight.txt'
import os
def main():
    while True:
        mainmenu()
        choice = int(input("请选择您的服务类型："))
        if choice in [0, 1, 2, 3, 4, 5, 6, 7]:
            if choice == 0:
                answer = input("您确定要退出系统吗？y/n:")
                if answer == 'y' or answer == 'Y':
                    print("谢谢您的使用！！！")
                    break
                else:
                    continue
            elif choice == 1:
                insert()
            elif choice == 2:
                search()
            elif choice == 3:
                delete()
            elif choice == 4:
                modify()
            elif choice == 5:
                show()

def mainmenu():
    print(
        "==========================================================机票管理系统============================================")
    print(
        "-----------------------------------------------------------主界面功能菜单-------------------------------------------------")
    print("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t1.录入航班信息")
    print("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2.查找航班信息")
    print("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t3.删除航班信息")
    print("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t4.修改航班信息")
    print("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t5.显示所有航班信息")
    print("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0.退出系统")
    print(
        "----------------------------------------------------------------------------------------------------------------------------")


def insert():
    flight_list = []
    while True:
        fno = input("请输入航班号（如1001）：")
        if not fno:
            break
            #endplace = input("请输入终点：")
        try:
            startplace = input("请输入起点：")
            endplace = input("请输入终点：")
            date = input("请输入日期：")
            price = int(input("请输入票价："))
            tickettype = input("请输入舱型：")
        except:
            print("输入错误，请重新输入！！！")
            continue

        # 录入信息保存
        flight = {'fno': fno, 'startplace': startplace, 'endplace': endplace, 'date': date, 'price': price, 'tickettype': tickettype}
        # 添加到列表中
        flight_list.append(flight)
        answer = input("请选择是否继续添加y/n：")
        if answer == 'y' or answer == 'Y':
            continue
        else:
            break
    save(flight_list)
    print("机票信息录入完毕！")


def save(lst):
    try:
        fli_txt = open(filename, 'a', encoding='utf-8')
    except:
        fli_txt = open(filename, 'w', encoding='utf-8')
    for item in lst:
        fli_txt.write(str(item) + '\n')
    fli_txt.close()

def search():
    flight_query = []
    while True:
        fno = ''
        startplace = ''
        if os.path.exists(filename):
            mode = input("按航班号查询请输入1，按起点查询请输入2：")
            if mode == '1':
                fno = input("请输入航班号：")
            elif mode == '2':
                startplace = input("请输入起点名：")
            else:
                print("您的输入有误，请重新输入！")
                search()
            with open(filename, 'r', encoding='utf-8') as rfile:
                flight = rfile.readlines()
                for item in flight:
                    d = dict(eval(item))
                    if fno != '':
                        if d['fno'] == fno:
                            flight_query.append(d)
                    elif startplace != '':
                        if d['startplace'] == startplace:
                            flight_query.append(d)
            show_flight(flight_query)
            flight_query.clear()
            answer = input("请选择是否继续查找y/n:")
            if answer == 'y' or answer == 'Y':
                continue
            else:
                break

        else:
            print("此航班未保存！")
            return
def show_flight(lst):
    if len(lst) == 0:
        print("没有此航班信息，无数据显示！！！")
        return

#定义格式
    format_title = '{:^6}\t{:^10}\t{:^10}\t{:^20}\t{:^8}\t{:^8}'
    print(format_title.format('航班号', '起点', '终点', '日期', '票价', '舱型', ))
    format_data = '{:^6}\t{:^12}\t{:^10}\t{:^12}\t{:^12}\t{:^9}'
    for item in lst:
        print(format_data.format(item.get('fno'),
                                 item.get('startplace'),
                                 item.get('endplace'),
                                 item.get('date'),
                                 item.get('price'),
                                 item.get('tickettype'),
                                     ))

def delete():
    while True:
        flight_id = input("请输入删除航班号：")
        if flight_id != '':
            if os.path.exists(filename):
                with open(filename, 'r', encoding='utf-8') as file:
                    flight_old = file.readlines()
            else:
                flight_old = []
            flag = False
            if flight_old:
                with open(filename,  'w', encoding='utf-8') as wfile:
                    d = {}
                    for item in flight_old:
                        d = dict(eval(item))
                        if d['fno'] != flight_id:
                            wfile.write(str(d)+'\n')
                        else:
                            flag = True
                    if flag:
                        print(f"航班号为{flight_id}的航班已被删除")
                    else:
                        print(f"未找到航班号为{flight_id}的航班")
            else:
                print("无航班信息")
                break
            show()
            answer = input("请选择是否继续删除y/n:")
            if answer == 'y' or answer == 'Y':
                continue
            else:
                break

def modify():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            flight_old = rfile.readlines()
    else:
        return
    flight_id = input("请输入要修改的航班号：")
    with open(filename, 'w', encoding='utf-8') as wfile:
        for item in flight_old:
            d = dict(eval(item))
            if d['id'] == flight_id:
                print("找到了这趟航班，可以修改信息")
                while True:
                    try:
                        d['startplace'] = input("请输入起点：")
                        d['endplace'] = input("请输入终点：")
                        d['date'] = input("请输入日期：")
                        d['price'] = input("请输入票价：")
                        d['tickettype'] = input("请输舱型：")
                    except:
                        print("您的输入有误，请重新输入！")
                    else:
                        break
                wfile.write(str(d)+'\n')
                print("修改成功")
            else:
                wfile.write(str(d) + '\n')
        answer = input("请选择是否修改y/n:")
        if answer == 'y' or answer == 'Y':
            modify()

def show():
    flight_list = []
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            flights = rfile.readlines()
            for item in flights:
                flight_list.append(eval(item))
            if flight_list:
                show_flight(flight_list)
    else:
        print("还没有录入数据")
if __name__ == '__main__':
    main()



